﻿using System;
using System.Data;
using Ext.Net;
using BLL;
using Roles;

namespace ERP.Modules
{
    public partial class Materials : System.Web.UI.UserControl
    {
        private readonly Materials_BLL _clsMaterials = new Materials_BLL();
        private readonly Materials_Type_BLL _clsMaterialsType =new Materials_Type_BLL();
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!X.IsAjaxRequest)
            {
                CheckPermisstion();
                GetMaterialsType();
                GetData();
                btnEdit.Disable(true);
                btnDel.Disable(true);
                btnExport.Disable(true);
                WindowsMaterials_Type();
                WindowsUnit();
                WindowsManufacturer();
                WindowsNational();
            }
        }
        //-------Store-Datasource-----------------
        protected void StoreMaterials_RefreshData(object sender, StoreReadDataEventArgs e)
        {
            txtSearch.Text = string.Empty;
            SelectBoxMaterialsMaterialsType.Text = string.Empty;
            GetData();
            GetMaterialsType();
        }
        //--------Buttom-Main------------------------
        protected void btnAddNew_Click(object sender, DirectEventArgs e)
        {
            GetComboBox();
            ClearTextBox();
            WindowsMaterials.Show();
        }
        protected void btnEdit_Click(object sender, DirectEventArgs e)
        {
            var sm = grMaterials.GetSelectionModel() as CheckboxSelectionModel;
            if (sm != null)
                foreach (var row in sm.SelectedRows)
                {
                    GetComboBox();
                    ClearTextBox();
                    DataDetail(int.Parse(row.RecordID));
                    WindowsMaterials.Show();
                    sm.UpdateSelection();
                }
        }

        protected void btnDel_Click(object sender, DirectEventArgs e)
        {
            var sm = grMaterials.GetSelectionModel() as CheckboxSelectionModel;
            if (sm != null)
                foreach (var row in sm.SelectedRows)
                {
                    try
                    {
                        Materials_BLL.DeleteMaterials(int.Parse(row.RecordID));
                    }
                    catch (Exception)
                    {
                        HTML.clsFormat.Alert_ERROR("Thông Báo", "Tồn tại tài liệu con, không xoá được vui lòng xoá tài liệu con trước !");
                    }
                }
            GetData();
        }
        protected void SelectBoxMaterialsMaterialsType_Change(object sender, DirectEventArgs e)
        {
            GetData();
        }
        //--------Buttom-Popup------------------------
        protected void btnSavePopUp_Click(object sender, DirectEventArgs e)
        {
            if (txtMaterials_ID.Text == string.Empty)
            {
                InsertMaterials();
            }
            else
            {
                if (CheckPermisstionDobclick())
                {
                    HTML.clsFormat.Alert_ERROR("Thông Báo", "Bạn không được cấp quyền để sửa đổi !");
                }
                else
                {
                    UpdateMaterials();
                }
            }
        }
        protected void btnCancelPopUp_Click(object sender, DirectEventArgs e)
        {
            WindowsMaterials.Close();
        }
        //----------Click-------------------
        protected void MaterialsDblClick(object sender, DirectEventArgs e)
        {
            GetComboBox();
            ClearTextBox();
            int Materials_Id = int.Parse(e.ExtraParams["Materials_Id"]);
            DataDetail(Materials_Id);
            WindowsMaterials.Show();
        }
        //----------Button-Windows---------------
        #region[Method]
        private void GetData()
        {
            if (String.IsNullOrEmpty(SelectBoxMaterialsMaterialsType.Text))
            {
                DataTable dtMaterials = _clsMaterials.Search(string.Empty);
                if (dtMaterials != null && dtMaterials.Rows.Count > 0)
                {
                    StoreMaterials.DataSource = dtMaterials;
                    StoreMaterials.DataBind();
                }
                else
                {
                    grMaterials.GetStore().RemoveAll();
                }
            }
            else
            {
                DataTable dtMaterials =
                    _clsMaterials.GetMaterialFillter(int.Parse(SelectBoxMaterialsMaterialsType.SelectedItem.Value));
                if (dtMaterials != null && dtMaterials.Rows.Count > 0)
                {
                    StoreMaterials.DataSource = dtMaterials;
                    StoreMaterials.DataBind();
                }
                else
                {
                    grMaterials.GetStore().RemoveAll();
                }
            }
        }
        private void DataDetail(int id)
        {
            DataTable dtMaterials = _clsMaterials.GetMaterialsDetail_Edit(id);
            if (dtMaterials != null && dtMaterials.Rows.Count > 0)
            {
                txtMaterials_ID.Text = dtMaterials.Rows[0]["Materials_ID"].ToString();
                txtMaterials_Alias.Text = dtMaterials.Rows[0]["Materials_Alias"].ToString();
                txtMaterials_Name.Text = dtMaterials.Rows[0]["Materials_Name"].ToString();
                txtMaterials_Tankage.Text = dtMaterials.Rows[0]["Materials_Tankage"].ToString();
                cbUnit.SetValue(int.Parse(dtMaterials.Rows[0]["Unit_Id"].ToString()));
                cbMaterials_Type.SetValue(int.Parse(dtMaterials.Rows[0]["Materials_Type_Id"].ToString()));
                cbMaterialsNational.SetValue(int.Parse(dtMaterials.Rows[0]["National_Id"].ToString()));
                cbMaterialsManufacture.SetValue(int.Parse(dtMaterials.Rows[0]["ID_Manufacturer"].ToString()));
                txtDateOfManufacture.Text = dtMaterials.Rows[0]["DateOfManufacture"].ToString();
                txtVAT.Text = dtMaterials.Rows[0]["VAT"].ToString();
                txtNote.Text = dtMaterials.Rows[0]["Note"].ToString();
                txtDayWarranty.Text = dtMaterials.Rows[0]["DayWarranty"].ToString();
                txtPrice_Initially.Text = dtMaterials.Rows[0]["Price_Initially"].ToString();
            }
        }
        private bool CheckInsert()
        {
            bool kiemtra = false;
            var clsMaterials = new Materials_BLL();
            var dtMaterials = clsMaterials.GetMaterials();
            if (dtMaterials != null && dtMaterials.Rows.Count > 0)
            {
                foreach (DataRow dr in dtMaterials.Rows)
                {
                    if (txtMaterials_ID.Text != dr["Materials_ID"].ToString())
                    {
                        if (txtMaterials_Alias.Text == dr["Materials_Alias"].ToString())
                        {
                            kiemtra = true;
                            HTML.clsFormat.Alert_ERROR("Thông Báo", "Mã vật tư đã tồn tại !");
                        }
                        else if (txtMaterials_Name.Text == dr["Materials_Name"].ToString())
                        {
                            kiemtra = true;
                            HTML.clsFormat.Alert_ERROR("Thông Báo", "Tên vật tư đã tồn tại !");
                        }
                    }
                }
            }
            return kiemtra;
        }
        private void InsertMaterials()
        {
            try
            {
                if (!CheckInsert())
                {
                    var obj = new ET.Materials_ET
                    {
                        Materials_Alias = txtMaterials_Alias.Text,
                        Materials_Name = txtMaterials_Name.Text,
                        Materials_Tankage = 0,
                        Unit_Id = int.Parse(cbUnit.SelectedItem.Value),
                        Materials_Type_Id = int.Parse(cbMaterials_Type.SelectedItem.Value),
                        National_Id = int.Parse(cbMaterialsNational.SelectedItem.Value),
                        ID_Manufacturer = int.Parse(cbMaterialsManufacture.SelectedItem.Value),
                        Price_Initially = float.Parse(txtPrice_Initially.Text),
                        DateOfManufacture = DateTime.Parse(txtDateOfManufacture.Text),
                        VAT = int.Parse(txtVAT.Text),
                        Note = txtNote.Text,
                        DayWarranty = txtDayWarranty.Text
                    };
                    Materials_BLL.InsertMaterials(obj);
                    HTML.clsFormat.Alert_INFO("Thông Báo", "Thêm mới thành công !");
                    GetData();
                    GetComboBox();
                    ClearTextBox();
                }
            }
            catch (Exception ex)
            {
                HTML.clsFormat.Alert_ERROR("Lỗi", ex.Message);
            }
        }
        private void UpdateMaterials()
        {
            try
            {
                if (!CheckInsert())
                {
                    var obj = new ET.Materials_ET
                    {
                        Materials_Id = int.Parse(txtMaterials_ID.Text),
                        Materials_Alias = txtMaterials_Alias.Text,
                        Materials_Name = txtMaterials_Name.Text,
                        Materials_Tankage = 0,
                        Unit_Id = int.Parse(cbUnit.SelectedItem.Value),
                        Materials_Type_Id = int.Parse(cbMaterials_Type.SelectedItem.Value),
                        National_Id = int.Parse(cbMaterialsNational.SelectedItem.Value),
                        ID_Manufacturer = int.Parse(cbMaterialsManufacture.SelectedItem.Value),
                        Price_Initially = float.Parse(txtPrice_Initially.Text),
                        DateOfManufacture = DateTime.Parse(txtDateOfManufacture.Text),
                        VAT = int.Parse(txtVAT.Text),
                        Note = txtNote.Text,
                        DayWarranty = txtDayWarranty.Text
                    };

                    Materials_BLL.UpdateMaterials(obj);
                    WindowsMaterials.Close();
                    HTML.clsFormat.Alert_INFO("Thông Báo", "Sữa thành công!");
                    GetData();
                }
            }
            catch (Exception ex)
            {
                HTML.clsFormat.Alert_ERROR("Lỗi", ex.Message);
            }
        }
        private void GetMaterialsType()
        {
            var _dtMaterialType = _clsMaterialsType.GetMaterials_Type();
            if (_dtMaterialType != null && _dtMaterialType.Rows.Count > 0)
            {
                StoreMaterialsMaterialsType.DataSource = _dtMaterialType;
                StoreMaterialsMaterialsType.DataBind();
            }
            else
            {
                SelectBoxMaterialsMaterialsType.GetStore().RemoveAll();
            }
        }
        #endregion

        #region [ComboBox]
        protected void GetComboBox()
        {
            var clsMaterials_Type = new Materials_Type_BLL();
            var dtMaterials_Type = clsMaterials_Type.Search(string.Empty);
            if (dtMaterials_Type != null && dtMaterials_Type.Rows.Count > 0)
            {
                Materials_TypeStore.DataSource = dtMaterials_Type;
                Materials_TypeStore.DataBind();
            }

            var clsUnit = new Unit_BLL();
            var dtUnit = clsUnit.Search(string.Empty);
            if (dtUnit != null && dtUnit.Rows.Count > 0)
            {
                UnitStore.DataSource = dtUnit;
                UnitStore.DataBind();
            }
            var clsNational = new National_BLL();
            var dtNational = clsNational.BindGirdNational(string.Empty);
            if (dtNational != null && dtNational.Rows.Count > 0)
            {
                StoreMaterialsNational.DataSource = dtNational;
                StoreMaterialsNational.DataBind();
            }
            var clsManufacturer = new BllManufacturer();
            var dtManufacturer = clsManufacturer.GetManufacturer(string.Empty);
            if (dtManufacturer != null && dtManufacturer.Rows.Count > 0)
            {
                StoreMaterialsManufacture.DataSource = dtManufacturer;
                StoreMaterialsManufacture.DataBind();
            }
        }
        protected void ReloadComboBox(object sender, StoreReadDataEventArgs e)
        {
            GetComboBox();
        }
        #endregion

        #region[ClearTextbox]
        protected void ClearTextBox()
        {

            txtMaterials_ID.Text = string.Empty;
            txtMaterials_Alias.Text = MaTuDong();
            txtMaterials_Name.Text = string.Empty;
            txtMaterials_Tankage.Text = "0";
            txtPrice_Initially.Text = "0";
            txtVAT.Text = "0";
            cbMaterials_Type.Clear();
            cbUnit.Clear();
            cbMaterialsManufacture.Clear();
            cbMaterialsNational.Clear();
        }
        #endregion

        #region[MaTangTuDong]
        protected string MaTuDong()
        {
            int i;
            DataTable dt = _clsMaterials.Search(string.Empty);
            if (dt != null && dt.Rows.Count > 0)
            {
                int max = int.Parse(dt.Rows[0]["Materials_ID"].ToString());
                for (i = 0; i < dt.Rows.Count; i++)
                {
                    if (int.Parse(dt.Rows[i]["Materials_ID"].ToString()) > max)
                    {
                        max = int.Parse(dt.Rows[i]["Materials_ID"].ToString());
                    }
                }
                i = max + 1;
            }
            else
            {
                i = 0;
            }
            return "VTDC00" + i;
        }
        #endregion

        #region[Search]
        protected void Search_Event(object sender, DirectEventArgs e)
        {
            var dtMaterials = _clsMaterials.Search(txtSearch.Text);
            if (dtMaterials != null && dtMaterials.Rows.Count > 0)
            {
                StoreMaterials.DataSource = dtMaterials;
                StoreMaterials.DataBind();
            }
        }
        #endregion

        #region[Permisstion]
        private void CheckPermisstion()
        {
            if (Session["login"] != null && Session["USer_Detail_Id"].ToString() != string.Empty)
            {
                bool Is_BtnAdd;
                bool Is_BtnEdit;
                bool Is_BtnView;
                bool Is_BtnDel;
                bool Is_BtnPrint;
                bool Is_BtnCancel;
                bool Is_BtnReview;

                SecurityServices.HasPermisstion_Btn(StringContent.VatTu, out Is_BtnAdd, out Is_BtnEdit, out Is_BtnDel, out Is_BtnView, out Is_BtnCancel, out Is_BtnPrint, out Is_BtnReview);
                if (Is_BtnAdd == false)
                {
                    btnAddNew.Visible = false;
                }
                if (Is_BtnEdit == false)
                {
                    btnEdit.Visible = false;
                }
                //if (Is_BtnView == false)
                //{
                //    PanelMaterialsA.Visible = false;
                //}
                if (Is_BtnDel == false)
                {
                    btnDel.Visible = false;
                }
                if (Is_BtnPrint == false)
                {
                    btnExport.Visible = false;
                }
            }
        }
        private bool CheckPermisstionDobclick()
        {
            var check = false;
            if (Session["login"] != null && Session["USer_Detail_Id"].ToString() != string.Empty)
            {
                bool Is_BtnAdd;
                bool Is_BtnEdit;
                bool Is_BtnView;
                bool Is_BtnDel;
                bool Is_BtnPrint;
                bool Is_BtnCancel;
                bool Is_BtnReview;

                SecurityServices.HasPermisstion_Btn(StringContent.VatTu, out Is_BtnAdd, out Is_BtnEdit, out Is_BtnDel, out Is_BtnView, out Is_BtnCancel, out Is_BtnPrint, out Is_BtnReview);
                if (Is_BtnEdit == false)
                {
                    check = true;
                }
            }
            return check;
        }
        #endregion

        private void WindowsMaterials_Type()
        {
            Window win = new Window()
            {
                ID = "WindowsMaterials_Type",
                Title = "Nhóm vật tư",
                Width = 829,
                Height = 400,
                Modal = true,
                AutoRender = false,
                Collapsible = false,
                Maximizable = true,
                Hidden = true,
                Loader = new ComponentLoader
                {
                    Url = "../PageParrent/Materials_Type.aspx",
                    Mode = LoadMode.Frame,
                    LoadMask =
                    {
                        ShowMask = true
                    }
                }
            };
            this.Controls.Add(win);
        }
        private void WindowsUnit()
        {
            Window win = new Window()
            {
                ID = "WindowsUnit",
                Title = "Đơn vị tính",
                Width = 829,
                Height = 400,
                Modal = true,
                AutoRender = false,
                Collapsible = false,
                Maximizable = true,
                Hidden = true,
                Loader = new ComponentLoader
                {
                    Url = "../PageParrent/Unit.aspx",
                    Mode = LoadMode.Frame,
                    LoadMask =
                    {
                        ShowMask = true
                    }
                }
            };
            this.Controls.Add(win);
        }
        private void WindowsManufacturer()
        {
            Window win = new Window()
            {
                ID = "Manufacturer",
                Title = "Hãng sản xuất",
                Width = 829,
                Height = 400,
                Modal = true,
                AutoRender = false,
                Collapsible = false,
                Maximizable = true,
                Hidden = true,
                Loader = new ComponentLoader
                {
                    Url = "../PageParrent/Manufacturer.aspx",
                    Mode = LoadMode.Frame,
                    LoadMask =
                    {
                        ShowMask = true
                    }
                }
            };
            this.Controls.Add(win);
        }
        private void WindowsNational()
        {
            Window win = new Window()
            {
                ID = "WindowsNational",
                Title = "Xuất xứ",
                Width = 829,
                Height = 400,
                Modal = true,
                AutoRender = false,
                Collapsible = false,
                Maximizable = true,
                Hidden = true,
                Loader = new ComponentLoader
                {
                    Url = "../PageParrent/National.aspx",
                    Mode = LoadMode.Frame,
                    LoadMask =
                    {
                        ShowMask = true
                    }
                }
            };
            this.Controls.Add(win);
        }
    }
}